const express = require('express')
const router = express.Router()
const favoritesDao = require('../database/favoritesDao')
// 根据用户id获取收藏列表
router.get('/getFavorites', async (req, res) => {
  let user_id = req.query.user_id
  try {
    let result = await favoritesDao.getFavorites(user_id)
    res.send({
      code: 200,
      msg: '获取成功',
      data: result
    })
  } catch (err) {
    res.send({
      code: 400,
      msg: '获取失败',
      data: err
    })
  }
})
// 新增用户收藏
router.put('/addFavorites', async (req, res) => {
  const { article_id, user_id } = req.body;

  try {
    // 检查是否已收藏
    const [existing] = await pool.execute(
      'SELECT id FROM favorites WHERE user_id = ? AND article_id = ?',
      [user_id, article_id]
    );

    // 防重复收藏逻辑
    if (existing.length > 0) {
      return res.status(400).json({
        code: 400,
        msg: '您已经收藏过该文章',
        data: null
      });
    }

    // 执行收藏
    const result = await favoritesDao.addFavorites(article_id, user_id);

    res.json({
      code: 200,
      msg: '收藏成功',
      data: result
    });
  } catch (err) {
    console.error('收藏失败:', err);

    // 处理MySQL唯一约束错误（错误码1062）
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({
        code: 400,
        msg: '请勿重复收藏',
        data: null
      });
    }

    res.status(500).json({
      code: 500,
      msg: '服务器内部错误',
      data: null
    });
  }
});

module.exports = router